 
#include <stdio.h>
#include "VinDefines.h"
#include "VinBitstreamIo.h"


VinBitstreamIO::VinBitstreamIO (UInt8* stream)
{
    bitstream = stream;
    bitCount  = 7;
}


VinBitstreamIO::~VinBitstreamIO ()
{
    bitstream = NULL;
    bitCount  = 0;
}
		
UInt32 VinBitstreamIO::GetBit ()
{
    UInt32 theBit = 0;
    theBit = (*bitstream >> bitCount--) & 0x01;
    if (bitCount < 0) {
        bitCount = 7;
        bitstream++;
    }
    return theBit;
}
		
UInt32 VinBitstreamIO::GetBits (UInt32 bitCount)
{
    UInt32 theElement = 0;
    while (bitCount-- > 0) {
        theElement |= GetBit();
        theElement <<= 1;
    }
    return theElement;
}
		
UInt32 VinBitstreamIO::GetUev ()
{
    UInt32 zeroCount = 0;
    UInt32 theBit    = 0;
    UInt32 uevByte   = 0;

    while ((theBit = GetBit()) != 1) {
        zeroCount++;
    }

    for (UInt32 bitCount = 0; bitCount < zeroCount; bitCount++) {
        theBit = GetBit();
        uevByte |= theBit;
        uevByte <<= 1;
    }

    UInt32 codeWord = (1 << zeroCount) + uevByte - 1;
    return codeWord;
}
		
UInt32 VinBitstreamIO::GetSev ()
{
    UInt32 sevCodeword = 0;
    UInt32 uevCodeword = GetUev();

    if (uevCodeword & 0x01 == 0) {
        sevCodeword = -(uevCodeword >> 1);
    } else {
        sevCodeword = (uevCodeword + 1) >> 1;
    }

    return sevCodeword;
}
		
UInt32 VinBitstreamIO::GetMev ()
{
    UInt32 mevCodeword = 0;
    UInt32 uevCodeword = GetUev();
    return uevCodeword;
}
